<template #file="{ file }">
    <div>
        <el-dialog v-model="props.isShow" :title="isAdd ? '添加商品分类' : '编辑商品分类'" center :before-close="closeX"  @open="open(formRef)">
            <el-form :model="form" label-width="80px" :rules="rules" ref="formRef">
                <el-form-item label="上级分类" prop="pid">
                    <el-select v-model="form.pid" placeholder="请选择">
                        <el-option label="顶级分类" value="0" />
                        <el-option v-for="item in store.getters['cate/getCate']" :key="item.id" :label="item.catename" :value="item.id" />
                    </el-select>
                </el-form-item>

                <el-form-item label="分类名称" prop="catename">
                    <el-input v-model="form.catename" />
                </el-form-item>

                <el-form-item label="图片" v-if="form.pid!=0">
                    <el-upload 
                    class="avatar-uploader" 
                    action="#"
                    :file-list="photo" 
                    :show-file-list="false" 
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                    :on-change="changeInfo"
                    :limit="1"
                    >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>

                <el-form-item label="状态">
                    <el-switch v-model="form.status" :active-value="1" :inactive-value="2" />
                </el-form-item>

            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="close()">取消</el-button>
                    <el-button type="primary" @click="submit(formRef)">确认</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import {cateadd,cateedit,cateinfo} from "@/request/api"
import { defineProps,defineEmits,defineExpose, ref, reactive } from 'vue';
import type { FormInstance, FormRules, UploadFile, UploadProps } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useStore } from "vuex";
let store = useStore()
let emit = defineEmits(['close'])

// 图片上传
let photo = ref()
const imageUrl = ref('')
const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    imageUrl.value = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('Avatar picture must be JPG format!')
        return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('Avatar picture size can not exceed 2MB!')
        return false
    }
    return true
}


// 获取ref
let formRef = ref<FormInstance>()

let form = ref({
    pid: null,//上级分类编号
    catename: "",//商品分类名称
    img: "",//图片(文件，一般用于二级分类)
    status: 2,//状态 1正常2禁用
    id:0
})

//定义 rules规则
let rules = reactive<FormRules>({
    catename: [
        { required: true, message: "请输入菜单名称", trigger: "blur" },
        { min: 2, max: 6, message: "Length should be 2 to 6", trigger: "blur" },
    ],
    pid: [
        {
            required: true,
            message: "请选择上级菜单",
            trigger: "change",
        },
    ],
});

let changeInfo = (file:any) =>{
    form.value.img = file.raw
} 

// 父子传参的接参
let props = defineProps({
    isAdd: Boolean,
    isShow: Boolean
})

// 请求上级分类
let getPid = () => {
  store.dispatch("cate/getCateListAction")
}
getPid()

// 关闭
let close = () => {
    emit("close")
}

const closeX = (done: any) => {
    done()
    close()
}

let open = (formEl: FormInstance | undefined) =>{
    if(!formEl) return
    form.value = {
    pid: null,//上级分类编号
    catename: "",//商品分类名称
    img: "",//图片(文件，一般用于二级分类)
    status: 2,//状态 1正常2禁用
    id:0
}
    formEl.resetFields();
    imageUrl.value = ''
}

let lookup = (id:number) =>{
    cateinfo({id}).then((res:any)=>{
        console.log(res);
        form.value = res.list
        form.value.id = id
        imageUrl.value = res.list.img
    })
}

let getCate = () =>{
  store.dispatch("cate/getCateListAction")
}

// 提交
let submit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((val) => {
        if (val) {
           if(props.isAdd){
            cateadd(form.value).then(res=>{
                if (res.code == 200) {
                        getCate()
                        close()
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
            })
           } else{
            cateedit(form.value).then(res=>{
                if (res.code == 200) {
                        getCate()
                        close()
                        ElMessage({
                            message: res.msg,
                            type: 'success',
                        })
                    } else {
                        ElMessage({
                            message: res.msg,
                            type: 'warning',
                        })
                    }
            })

           }
        }
    })
}

defineExpose({
    lookup
})
</script>


<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>